//$URL: http://dasding.googlecode.com/svn/branches/spring-security/api/src/main/java/de/piratech/dasding/api/rest/UserResource.java $
//$Id: UserResource.java 74 2012-10-22 18:17:47Z amuthmann@gmail.com $
/*
 * Copyright 2012 Piratech.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package de.piratech.dasding.api.rest;

import de.piratech.dasding.data.User;
import de.piratech.dasding.data.database.Database;
import de.piratech.dasding.data.helper.PasswordHelper;
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 *
 * All actions for users
 *
 * @author deveth0
 */
@Path("/users")
@Component
public class UserResource {
  @Autowired
  private Database database;
  
  private static final Logger LOG = LoggerFactory.getLogger(UserResource.class);

  /**
   * Creates a new user
   *
   * 
   *
   * POST
   *
   * @param login (required)
   * @param name (required)
   * @param password (required)
   * @param mail (required)
   * @param phone
   * @param mobile
   *
   * @return
   */
  @POST
  @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
  @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
  public User createUser(
          @FormParam("login") String login,
          @FormParam("name") String name,
          @FormParam("password") String password,
          @FormParam("phone") String phone,
          @FormParam("mobile") String mobile,
          @FormParam("mail") String mail) {
    LOG.debug("createUser(login={}, name={}, phone={}, mobile={}, mail={})", login, name, phone, mobile, mail);
    User user = new User();
    user.setId(login);
    user.setName(name);
    user.setPassword(PasswordHelper.getCryptedPassword(password, login));
    user.setMobile(mobile);
    user.setMail(mail);
    user.setPhone(phone);
    user.addRole(User.USER_ROLE.USER);
    if (!user.isValid()) {
      throw new IllegalArgumentException("Not all required fields are set");
    }
    return database.getUserData().createUser(user);
  }
}
